package com.treeliked.resource;

import com.treeliked.pojo.Response;
import com.treeliked.service.FileService;
import com.treeliked.service.impl.FileServiceImpl;
import com.treeliked.util.Constant;
import com.treeliked.util.FileUtils;
import com.treeliked.util.StringUtils;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import java.io.File;
import java.io.InputStream;

/**
 * 文件资源
 *
 * @author lqs2
 * @date 2018/11/30, Fri
 */
@Path("/file")
public class FileResource {

    private static Logger log = LoggerFactory.getLogger(FileResource.class);

    private static FileService fs = new FileServiceImpl();


    @GET
    @Path("/upload")
    @Produces(MediaType.TEXT_HTML)
    public InputStream openUploadPage() {
        return FileUtils.getResourceAsStream("templates/index.html");
    }

    @POST
    @Path("/upload-file")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    @Produces(MediaType.APPLICATION_JSON)
    public Response uploadFile(
            @FormDataParam("file") InputStream ips,
            @FormDataParam("name") String fileName,
            @FormDataParam("path") String filePath) {
        log.info("文件上传-> {}, 路径-> {}", fileName, filePath);
        Response resp = new Response();
        try {
            File file;
            if (StringUtils.isEmpty(filePath)) {
                file = new File(Constant.FILE_SAVE_BASE_URI + fileName);
            } else {
                file = new File(filePath + File.separator + fileName);
            }
            if (file.exists()) {
                file.delete();
            }
            fs.saveFile(ips, file);
            resp.setCode(Response.RESPONSE_OK);
            resp.setMessage("文件【" + fileName + "】上传完成");

        } catch (Exception e) {
            log.error("", e);
            FolderResource.packServerErrorResponse(resp);
        }
        return resp;
    }


    @GET
    @Path("/download/{path : .+}")
    @Produces(MediaType.APPLICATION_JSON)
    public javax.ws.rs.core.Response downloadFile(@Context UriInfo uriInfo) {
        String path = FolderResource.getExpectedParams(uriInfo, 14);
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        log.info("文件下载-> {}", fileName);
        File file = new File(path);
        if (!file.exists()) {
            Response resp = new Response();
            resp.setCode(Response.RESPONSE_BAD_REQUEST);
            resp.setMessage("文件【" + path + "】不存在");
            return javax.ws.rs.core.Response.ok(resp, MediaType.APPLICATION_JSON).build();
        }
        return javax.ws.rs.core.Response
                .ok(file)
                .header("Content-disposition", "attachment;filename=" + fileName)
                .header("Cache-Control", "no-cache").build();
    }


}
